package artid.com.arttogoa.fragment;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import artid.com.arttogoa.HomeActivity;
import artid.com.arttogoa.R;
import artid.com.arttogoa.adapter.FolersAdapter;
import artid.com.arttogoa.adapter.GridAdapter;
import artid.com.arttogoa.db.SDCache;
import artid.com.arttogoa.parser.FilesBean;
import artid.com.arttogoa.parser.FolderBean;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.MD5;
import artid.com.arttogoa.util.MySharedPreferences;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.volley.VolleyRequest;
import artid.com.arttogoa.xml.FilesBeanParserImpl;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

public class SDFragment extends Fragment {
	private TextView text;
	private List<FilesBean> filesList;
	private List<FolderBean> folderList;
	private GridView gridView;
	private ListView listView;
	// private ImageView iv;
	private Activity mContext;
	private LinearLayout info;
	private Button wifi;
	View v;
	private boolean Multiple = true;
	private float w, h;

	public SDFragment(float w, float h) {
		// TODO Auto-generated constructor stub
		this.w = w;
		this.h = h;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
	 * android.view.ViewGroup, android.os.Bundle)
	 */
	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		v = inflater.inflate(R.layout.activity_driver, null);
		mContext = getActivity();
		info = (LinearLayout) v.findViewById(R.id.ll_info);
		listView = (ListView) v.findViewById(R.id.list);
		wifi = (Button) v.findViewById(R.id.btn_complete);
		gridView = (GridView) v.findViewById(R.id.grid);
		wifi.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (android.os.Build.VERSION.SDK_INT > 10) {
					// 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
					startActivity(new Intent(
							android.provider.Settings.ACTION_WIFI_SETTINGS));
				} else {
					startActivity(new Intent(
							android.provider.Settings.ACTION_WIFI_SETTINGS));
				}
			}
		});

		return v;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		// TODO Auto-generated method stub

		super.onResume();
		initFoldersVolley();
		initMacVolley();
	}

	/**
	 * 
	 */
	private void initData(String str) {
		// TODO Auto-generated method stub
		// 初始化自定义的实现类BeautyParserImpl
		FilesBeanParserImpl pbp = new FilesBeanParserImpl();
		// 调用pbp的parse()方法，将输入流传进去解析，返回的链表结果赋给beautyList
		try {
			filesList = pbp.parse(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block b
			e.printStackTrace();
		}
		System.out.println(filesList.toString());
		setupViews();
	}

	/**
	 * 
	 */
	private void initFolderData(String str) {
		// TODO Auto-generated method stub
		// 初始化自定义的实现类BeautyParserImpl
		FilesBeanParserImpl pbp = new FilesBeanParserImpl();
		// 调用pbp的parse()方法，将输入流传进去解析，返回的链表结果赋给beautyList
		try {
			folderList = pbp.parseF(str);
		} catch (Exception e) {
			// TODO Auto-generated catch block b
			e.printStackTrace();
		}
		folersViews();
		System.out.println("folderList=" + folderList.toString());
	}

	/**
	 * 解析MAC地址
	 */
	private void initMacData(String str) {
		// TODO Auto-generated method stub
		// 初始化自定义的实现类BeautyParserImpl
		System.out.println(str);
		String mac = str.contains("<mac>") ? str.substring(
				str.indexOf("<mac>") + 5, str.indexOf("</mac>")) : "";
		// FilesBeanParserImpl pbp = new FilesBeanParserImpl();
		// // 调用pbp的parse()方法，将输入流传进去解析，返回的链表结果赋给beautyList
		// try {
		// mac = pbp.parseMac(str);
		// } catch (Exception e) {
		// // TODO Auto-generated catch block b
		// e.printStackTrace();
		// }
		System.out.println("mac=" + mac);
		MySharedPreferences.getMySharedPreferences(mContext).setValue("mac",
				mac);
	}

	String path;
	int index;
	private Dialog progressDialog;
	private FolersAdapter mFolersAdapter;
	private GridAdapter mGridAdapter;

	/**
	 * 将目录显示到手机界面上
	 */
	private void folersViews() {
		if (folderList.size() < 2) {
			Multiple = false;
			initFilesVolley(folderList.get(0).getName());
			return;
		}
		mFolersAdapter = new FolersAdapter(mContext, folderList);
		listView.setAdapter(mFolersAdapter);
		listView.setVisibility(View.VISIBLE);
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				initFilesVolley(folderList.get(arg2).getName());
			}
		});
		progressDialog.dismiss();
	}

	/**
	 * 将图片显示到手机界面上
	 */
	private void setupViews() {
		String mac = MySharedPreferences.getMySharedPreferences(mContext)
				.getValue("mac", "");
		System.out.println("mac=" + mac);
		if (TextUtils.isEmpty(mac)) {
			initMacVolley();
		}

		mGridAdapter = new GridAdapter(mContext, filesList, SDCache.WIDISD,
				gridView, Multiple, null);
		gridView.setAdapter(mGridAdapter);
		gridView.setVisibility(View.VISIBLE);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				index = Multiple ? arg2 - 1 : arg2;
				if (progressDialog != null && !progressDialog.isShowing())
					progressDialog.show();
				path = filesList.get(index).getImgURL();
				new Thread(networkTask).start();
			}
		});
	}

	private FilesBean fb;
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			// Uri urlb = (Uri) msg.obj;
			// if (urlb != null) {
			// iv.setImageURI(urlb);
			// }
			switch (msg.what) {
			case 1:
				Intent intent = new Intent(mContext, HomeActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("image", fb);
				intent.putExtras(bundle);
				mContext.setResult(3, intent);// 返回页面1
				mContext.finish();
				break;
			case 2:
				AlertUtils.initSubmitSumAlertDialog(getActivity(),
						"该图片质量不够，请换一张图片作为完整图");
				break;
			default:
				break;
			}

			// TODO
			// UI界面的更新等相关操作
		}
	};

	/**
	 * 网络操作相关的子线程
	 */
	Runnable networkTask = new Runnable() {

		@Override
		public void run() {
			// TODO
			// 在这里进行 http request.网络请求相关操作
			// Uri urlb = null;
			path = filesList.get(index).getImgURL();
			// FileOutputStream outStream;
			String name = MD5.getMD5(path) + ".JPG";
			File file = new File(getSDPath() + "/SD", name);
			File destDir = new File(getSDPath() + "/SD");
			if (!destDir.exists()) {
				destDir.mkdirs();
			}
			if (!file.exists()) {
				// 从网络上获取图片
				URL url;
				try {
					url = new URL(path);

					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(5000);
					conn.setRequestMethod("GET");
					conn.setDoInput(true);
					if (conn.getResponseCode() == 200) {

						InputStream is = conn.getInputStream();
						FileOutputStream fos = new FileOutputStream(file);
						byte[] buffer = new byte[1024];
						int len = 0;
						while ((len = is.read(buffer)) != -1) {
							fos.write(buffer, 0, len);
						}
						is.close();
						fos.close();
						// 返回一个URI对象
						// return Uri.fromFile(file);
					}
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (w > 0 || h > 0) {
				BitmapFactory.Options options = new BitmapFactory.Options();

				/**
				 * 最关键在此，把options.inJustDecodeBounds = true;
				 * 这里再decodeFile()，返回的bitmap为空
				 * ，但此时调用options.outHeight时，已经包含了图片的高了
				 */
				options.inJustDecodeBounds = true;
				Bitmap bitmap = BitmapFactory.decodeFile(getSDPath() + "/SD/"
						+ name, options); // 此时返回的bitmap为null
				/**
				 * options.outHeight为原始图片的高
				 */
				Log.e("Test", "Bitmap Height == " + options.outHeight);
				if (options.outHeight < h || options.outWidth < w) {
					Message msg = new Message();
					msg.what = 2;
					handler.sendMessage(msg);
					return;
				}
			}
			Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
			Uri uri = Uri.fromFile(file);
			intent.setData(uri);
			getActivity().sendBroadcast(intent);
			fb = filesList.get(index);

			fb.setImgURL(getSDPath() + "/SD/" + name);
			Message msg = new Message();
			msg.what = 1;
			msg.obj = Uri.fromFile(file);
			handler.sendMessage(msg);
		}
	};

	/**
	 * 
	 */
	private void initFoldersVolley() {
		// TODO Auto-generated method stub
		showLoding(mContext);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mQueue.add(foldersRequest);
	}

	/**
	 * 获取mac地址
	 */
	private void initMacVolley() {
		// TODO Auto-generated method stub
		// showLoding(mContext);
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mQueue.add(MacRequest);
	}

	public void saveFile(Bitmap bm, String fileName, String path)
			throws IOException {
		String subForder = getSDPath() + path;
		File foder = new File(subForder);
		if (!foder.exists()) {
			foder.mkdirs();
		}
		File myCaptureFile = new File(subForder, fileName);
		if (!myCaptureFile.exists()) {
			myCaptureFile.createNewFile();
		}
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
		fb = filesList.get(index);
		fb.setImgURL(getSDPath() + "/SD/" + fileName);
		Intent intent = new Intent(mContext, HomeActivity.class);
		Bundle bundle = new Bundle();
		bundle.putSerializable("image", fb);
		intent.putExtras(bundle);
		mContext.setResult(3, intent);// 返回页面1
		mContext.finish();
	}

	/**
	 * 
	 */
	private void initFilesVolley(String name) {
		// TODO Auto-generated method stub
		if (progressDialog != null && !progressDialog.isShowing())
			progressDialog.show();
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		VolleyRequest filesRequest = new VolleyRequest(Request.Method.GET,
				SDCache.GetFiles + name, new Listener<String>() {

					@Override
					public void onResponse(String s) {
						System.out.println(s);

						MySharedPreferences.getMySharedPreferences(mContext)
								.setValue(MySharedPreferences.EZSHARE_WIFI,
										NetUtils.getSSID(mContext));
						progressDialog.dismiss();
						gridView.setVisibility(View.VISIBLE);
						info.setVisibility(View.GONE);
						initData(s);
					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError volleyError) {
						progressDialog.dismiss();
						Log.e("volleyerror", "erro2");
						//
						gridView.setVisibility(View.GONE);
						info.setVisibility(View.VISIBLE);
						// text.setText("erro2");
					}
				});
		mQueue.add(filesRequest);
	}

	VolleyRequest MacRequest = new VolleyRequest(Request.Method.GET,
			SDCache.devicemac, new Listener<String>() {

				@Override
				public void onResponse(String s) {
					initMacData(s);
				}
			}, new ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError volleyError) {

				}
			});
	VolleyRequest foldersRequest = new VolleyRequest(Request.Method.GET,
			SDCache.GetFolders, new Listener<String>() {

				@Override
				public void onResponse(String s) {
					System.out.println(s);

					listView.setVisibility(View.VISIBLE);
					info.setVisibility(View.GONE);
					initFolderData(s);
				}
			}, new ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError volleyError) {
					progressDialog.dismiss();
					Log.e("volleyerror", "erro2");
					//
					listView.setVisibility(View.GONE);
					info.setVisibility(View.VISIBLE);
					// text.setText("erro2");
				}
			});

	public static String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		}
		return sdDir.toString();
	}

	public void showLoding(Context activity) {
		if (progressDialog == null) {
			LayoutInflater inflater = LayoutInflater.from(activity);
			View v = inflater.inflate(R.layout.loading, null);// 得到加载view
			RelativeLayout layout = (RelativeLayout) v
					.findViewById(R.id.rel_dialog);// 加载布局
			progressDialog = new Dialog(activity, R.style.dialog);// 创建自定义样式dialog
			progressDialog.setCancelable(false);// 不可以用“返回键”取消
			progressDialog.setContentView(layout,
					new LinearLayout.LayoutParams(
							LinearLayout.LayoutParams.FILL_PARENT,
							LinearLayout.LayoutParams.FILL_PARENT));// 设置布局
		}
		if (!progressDialog.isShowing()) {
			progressDialog.show();
		}
	}
}
